<?php
/**
 * FastApp.
 * 10/19/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp\Api\Service\Account;

use App\Fastapp\Api\Service\BaseService;
use App\Fastapp\Model\AccountSetting;

class AccountSettingService extends BaseService
{
    public static function config(int $uid = 0): array
    {
        $uid = $uid ?: get_uid();
        return AccountSetting::query()->where(['user_id' => $uid])->pluck('val', 'key')->toArray();
    }

    public static function update(array $config, int $uid = 0): bool
    {
        $uid = $uid ?: get_uid();
        foreach ($config as $k => $v) {
            self::upOrCreate($k, $v, $uid);
        }
        return true;
    }

    public static function upOrCreate(string $k, string|int $v, int $user_id = 0): bool|int
    {
        $md = AccountSetting::query()->firstOrCreate(['user_id' => $user_id, 'key' => $k]);
        return $md->update(['val' => $v]);
    }

    public static function setTransactionPassword(string $password, int $uid = 0, bool $reset = false): bool
    {
        if (!$reset && AccountSetting::query()->where(['user_id' => $uid, 'key' => 'transaction_password'])->exists()) return false;
        return self::upOrCreate('transaction_password', $password, $uid);
    }
}